const { app, BrowserWindow ,session } = require('electron')
const path = require('path')

let win = null
app.whenReady().then(()=>{
    createWindow()
})

function createWindow() {
    win = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            webviewTag: true // 开启webview标签
          }
    })
    customUA()
    redirect()
    win.loadFile(path.join(__dirname,'../renderer/index.html'))
    win.webContents.openDevTools({mode: 'bottom'})
}

// 自定义UA
function customUA() {
    const filter = {
        urls: ['https://*.github.com/*'],
      }
    session.defaultSession.webRequest.onBeforeSendHeaders(filter,(details,callback)=>{
        details.requestHeaders['User-Agent'] = 'qingyi-macbook'
        callback({ requestHeaders: details.requestHeaders})
    })
}

// 设置允许跨域
function setAllowCors() {
    const filter = {
        urls: ['http://localhost:*/*'],
      }
    win.webContents.session.webRequest.onHeadersReveiced(filter,(details,callback)=>{
        details.responseHeaders['Access-Control-Allow-Origin'] = ['*']
        callback({responseHeaders:details.responseHeaders})
    })
}

// 请求转发
function redirect() {
    const filter = {
        urls: []
    }
    win.webContents.session.webRequest.onBeforeRequest(filter,(details,callback)=>{
        const { url, resourceType} = details
        const response = { cacel: false }
        if(resourceType === 'image' && url.startsWith('https://dlweb.sogoucdn.com/pcsearch/web/index/images/logo')) {
            console.log(response,'r')
            response.redirectURL = 'https://www.baidu.com/img/PCfb_5bf082d29588c07f842ccde3f97243ea.png'
        }
        callback(response)
    })
}